package com.tencent.cloud.iov.util;

import android.text.TextUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

/**
 * 字符串工具类
 *
 * @author showxiao
 * @date 2018/9/23
 */
public class StringUtils {

    private static final String LIST_STRING_SPLITTER = ",";

    private StringUtils() {
    }

    public static <T> String listToString(List<T> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }

        StringBuilder strBuilder = new StringBuilder();
        for (T item : list) {
            strBuilder.append(item).append(LIST_STRING_SPLITTER);
        }

        String str = strBuilder.toString();
        return str.substring(0, str.length() - 1);
    }

    public static <T> List<T> stringToList(String str) {
        if (TextUtils.isEmpty(str)) {
            return Collections.emptyList();
        }

        String[] strings = str.split(LIST_STRING_SPLITTER);
        List<T> list = new ArrayList<>();
        for (String string : strings) {
            list.add((T) string);
        }

        return list;
    }

    /**
     * 用 '*' 隐藏车辆信息
     *
     * @param carInfoValue
     * @return
     */
    public static boolean hideCarInfo(StringBuffer carInfoValue) {
        if (TextUtils.isEmpty(carInfoValue)) {
            return false;
        }
        return replaceString(carInfoValue, 2, carInfoValue.length() - 2, '*');
    }

    /**
     * 将源字符串source中[beginIndex, endIndex]字符依次替换为newChar
     * <p>
     * 注：替换失败返回源字符串
     *
     * @param source     源字符串
     * @param beginIndex 源字符串中要替换的字符串的开始下标
     * @param endIndex   源字符串中要替换的字符串的结束下标
     * @param newChar    新字符
     * @return
     */
    public static boolean replaceString(StringBuffer source, int beginIndex,
                                        int endIndex, char newChar) {
        if (TextUtils.isEmpty(source)
                || beginIndex < 0
                || beginIndex >= endIndex
                || endIndex > source.length()) {
            return false;
        }
        StringBuffer replaceString = new StringBuffer();
        for (int i = 0; i < endIndex - beginIndex; ++i) {
            replaceString.append(newChar);
        }
        source.replace(beginIndex, endIndex, replaceString.toString());
        return true;
    }

    public static String format(String format, Object... args) {
        return String.format(Locale.getDefault(), format, args);
    }
}
